import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
    FooterToolbar,
    PageContainer, ProFormInstance,
    ProTable,
} from '@ant-design/pro-components';
import {Button, Drawer, Input, message, Modal, Dropdown, Tag} from 'antd';
import React, {useRef, useState} from 'react';
import type {OrganizationResourceListItem} from './data';
import {organizationResourceList, organizationResourceRecycle} from './service';
import {Link, useParams} from "react-router-dom";
import {ResourceTypeEnum} from "@/pages/order/data.enum";

const {confirm} = Modal;

const handleRecycle = async (selectedRows: OrganizationResourceListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
        await organizationResourceRecycle({
            orderIds: selectedRows.map((row) => row.orderId),
        });
        hide();
        message.success('删除成功，即将刷新');
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

const OrganizationResourceList: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const [selectedRowsState, setSelectedRows] = useState<OrganizationResourceListItem[]>([]);
    const proTableFormRef = useRef<ProFormInstance>();
    const pageParams: Record<string, any> = useParams();

    /** 国际化配置 */
    const columns: ProColumns<OrganizationResourceListItem>[] = [
        // {
        //     title: '租户',
        //     dataIndex: 'organizationId',
        //     search: true,
        //     valueType: 'select',
        //     hidden: true,
        //     request: async () => {
        //         const result = await organizationSelectList({});
        //         return (
        //             result.data?.map((item) => ({
        //                 label: item.name,
        //                 value: item.organizationId,
        //             })) || []
        //         );
        //     },
        // },
        {
            title: '租户名称',
            dataIndex: 'organizationName',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '资源类型',
            dataIndex: 'resourceType',
            search: true,
            hidden: true,
            valueType: 'select',
            valueEnum: ResourceTypeEnum,
        },
        {
            title: '资源类型',
            dataIndex: 'resourceTypeName',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '资源信息',
            dataIndex: 'resourceDesc',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '机房编号',
            dataIndex: 'machineRoomNo',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '机柜编号',
            dataIndex: 'cabinetNo',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: 'U位区间',
            dataIndex: 'uPosition',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '关联订单',
            dataIndex: 'orderId',
            valueType: 'text',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'text',
            search: false,
            render: (value, record, index) => {
                return <Tag color="blue"> 运行中 </Tag>;
            },
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '开通时间',
            dataIndex: 'createdAt',
            valueType: 'text',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            fixed: 'right',
            ellipsis: true,
            render: (_, record) => {
                return [
                    <a
                        key="config"
                        onClick={async () => {
                            confirm({
                                title: '资源回收',
                                // icon: <ExclamationCircleFilled />,
                                content: '回收此资源，同时账单将截止到现在，现在回收?',
                                onOk() {
                                    const list: OrganizationResourceListItem[] = [];
                                    list.push(record)
                                    handleRecycle(list);
                                    setSelectedRows([]);
                                    actionRef.current?.reloadAndRest?.();
                                    return true;
                                }
                            });
                        }}
                    >
                        回收
                    </a>,
                ]
            },
        },
    ];

    return (
        <PageContainer>
            <ProTable<OrganizationResourceListItem, API.ListPagination>
                headerTitle="租户资源列表"
                actionRef={actionRef}
                formRef={proTableFormRef}
                rowKey="orderId"
                search={{
                    labelWidth: 90,
                }}
                scroll={{x: true}}
                toolBarRender={() => [
                    <Link to={`/power/resource-activate/`+ pageParams?.id}>
                        <Button
                            type="primary"
                            key="primary"
                        >
                            <PlusOutlined/> 开通算力
                        </Button>
                    </Link>,
                ]}
                request={ (params, sort, filter) =>
                    organizationResourceList(params, {}, pageParams?.id) // Pass the fixed parameter to the function
                }
                columns={columns}
                rowSelection={{
                    onChange: (_, selectedRows) => {
                        setSelectedRows(selectedRows);
                    },
                }}
                options={{
                    density: true,
                    fullScreen: true,
                    reload:true,
                    setting: false
                }}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a
                                style={{
                                    fontWeight: 600,
                                }}
                            >
                                {selectedRowsState.length}
                            </a>{' '}
                            项 &nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            confirm({
                                title: '资源回收',
                                content: '回收此资源，同时账单将截止到现在，现在回收?',
                                onOk() {
                                    handleRecycle(selectedRowsState);
                                    setSelectedRows([]);
                                    actionRef.current?.reloadAndRest?.();
                                    return true;
                                }
                            });
                        }}
                    >
                        批量回收
                    </Button>
                </FooterToolbar>
            )}

        </PageContainer>
    );
};

export default OrganizationResourceList;
